$(function() {
    obj.init();
});

var obj = new function () {
    return {
        dataGrid: null,
        params: {
            type: 'userGroup',
            goal: null,
            goalId: null,
            target: null
        },
        dom: {
            save: null
        },
        init: function () {
            this.params.goal   = xhTool.getQuery('goal');
            this.params.goalId = xhTool.getQuery('goalId');
            this.params.target = xhTool.getQuery('target');

            this.dom.save = window.top.xhTop.getModalConfirmDom();

            this.dataGrid = new xhDataGrid($('#list'), 'Group/getGroup');
            this.dataGrid.init();

            this.listener();
        },
        listener: function () {
            var $this = this;
            //选中已有权限
            $this.dataGrid.onLoadSuccess = function (data) {
                $this.funObj().selectExistPower();
            };
            //保存权限
            $this.dom.save.click(function () {
                 $this.funObj().savePower();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                selectExistPower: function () {
                    xhExtra.ajaxRequest('Power/getExtraPower', $this.params, {check: true, success: false}, function (data) {
                        $.each(data.powerIds, function (index, id) {
                            $this.dataGrid.command('selectRow', id);
                        });
                    });
                },
                savePower: function () {
                    xhExtra.ajaxRequest('Power/saveExtraPower', $.extend({}, $this.params, {ids: $this.dataGrid.getSelectValues('iGroupId')}), {check: false, success: true}, function (result) {
                        if (xhExtra.checkError(result)) {
                            xhExtra.setBtnNormal($this.dom.save);
                            return false;
                        }
                        window.top.xhTop.closeModal();
                    });
                }
            }
        }
    }
};